package com.mxpio.erp.quality.controller;

import com.mxpio.erp.common.enums.InspectionEnums;
import com.mxpio.erp.common.quality.entity.InspectionBill;
import com.mxpio.erp.common.quality.entity.VInspectionBillRecord;
import com.mxpio.erp.common.quality.service.InspectionBillService;
import com.mxpio.erp.common.quality.service.VInspectionBillRecordService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.List;

@Tag(name = "InspectionBillController", description = "质检单据接口")
@RestController
@RequestMapping("/erp/quality/ib/")
public class InspectionBillController {
	
	@Autowired
	private InspectionBillService inspectionBillService;
	@Autowired
	private VInspectionBillRecordService inspectionBillRecordService;
	@GetMapping("list")
	@Operation(summary = "质检单列表", description = "获取质检单列表", method = "GET")
	public Result<List<InspectionBill>> list(Criteria criteria) throws UnsupportedEncodingException {
		List<InspectionBill> tos = inspectionBillService.list(InspectionBill.class, criteria);
		return Result.OK(tos);
	}
	
	@GetMapping("page")
	@Operation(summary = "质检单列表(分页)", description = "获取质检单列表(分页)", method = "GET")
	public Result<Page<InspectionBill>> page(Criteria criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
		Pageable pageAble = PageRequest.of(pageNo-1, pageSize);
		Page<InspectionBill> page = inspectionBillService.listPage(InspectionBill.class, pageAble, criteria);
		return Result.OK(page);
	}
	
	@GetMapping("list/{bizNo}")
	@Operation(summary = "根据bizNo获取质检单", description = "根据bizNo获取质检单", method = "GET")
	public Result<InspectionBill> getById(@PathVariable(name = "bizNo", required = true) String bizNo) {
		InspectionBill inspectionBill = inspectionBillService.getById(InspectionBill.class, bizNo);
		return Result.OK(inspectionBill);
	}
	
	@RequestMapping("save")
    @Operation(summary = "保存质检单", description = "保存质检单")
    public Result<InspectionBill> save(@RequestBody InspectionBill inspectionBill) {
		inspectionBillService.save(inspectionBill,new SmartCrudPolicyAdapter(){
        	/*@Override
        	public boolean beforeInsert(CrudContext context) {
        		Object o = context.getEntity();
        		if(o instanceof InQualityOrderLine){
        			InspectionBill inspectionBill = context.getParent();
                    ((InQualityOrderLine) o).setNoticeNo(inspectionBill.getNoticeNo());
        		}
        		return true;
        	}*/
        });
        return Result.OK(inspectionBill);
    }

	@PutMapping("judge/{bizNo}")
	@Operation(summary = "判定质检单", description = "判定质检单", method = "PUT")
	public Result<Object> judge(@PathVariable(name = "bizNo", required = true) String bizNo) {
		InspectionBill bill = inspectionBillService.getById(InspectionBill.class, bizNo);
		if (bill.getCheckStatus().equals(InspectionEnums.CheckStatus.FINISH.getCode())){
			return Result.error("单据已检验完成，不能重新判定！");
		}
		if (StringUtils.isBlank(bill.getTestResult())){
			return Result.error("单据未维护检验结论！");
		}
		return inspectionBillService.judge(bill,bill.getTestResult());
	}
	
	@DeleteMapping("remove/{bizNos}")
	@Operation(summary = "删除质检单", description = "删除质检单", method = "DELETE")
	public Result<InspectionBill> remove(@PathVariable(name = "bizNos", required = true) String bizNos) {
		String bizNo[] = bizNos.split(",");
		for(String key : bizNo){
			/*Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, key);
			inQualityOrderLineSerivce.removeBatch(InQualityOrderLine.class, c);*/
			inspectionBillService.delete(InspectionBill.class, key);
		}
		return Result.OK();
	}
	
    /*@PutMapping("submit/{bizNo}")
    @Operation(summary = "提交质检单", description = "提交质检单", method = "PUT")
    public Result<Object> submit(@PathVariable(name = "bizNo", required = true) String bizNo,
    		@RequestBody OrderExcuteVo orderExcuteVo) {
    	InspectionBill notice = inspectionBillService.getById(InspectionBill.class, bizNo);
		if (notice.getNoticeStatus().equals(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode())){
			return Result.error("单据状态已发生变化，已确认状态单据不允许重复确认！");
		}
    	NoticeContext context = noticeService.execute(notice, new DefaultInQualityOrderNoticePolicy(orderExcuteVo.getLines()));
    	if(CollectionUtils.isEmpty(context.getErrors())) {
    		return Result.OK();
    	}else {
    		return Result.error(context.getErrors().get(0));
    	}
    }*/

	/*@GetMapping("listbynos/{noticeNos}")
	@Operation(summary = "根据noticeNos获取对应质检单及明细", description = "根据noticeNos获取质检单及明细", method = "GET")
	public Result<List<InspectionBill>> getByIds(@PathVariable(name = "noticeNos", required = true) String noticeNos) {
		return inspectionBillService.listByIds(noticeNos);
	}

	@PutMapping("reject/{noticeNo}")
	@Operation(summary = "拒绝质检单", description = "拒绝质检单", method = "PUT")
	public Result<? extends Notice> close(@Parameter(description="质检单单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
		InspectionBill notice = inspectionBillService.getById(InspectionBill.class,noticeNo);
		return noticeService.updateNoticeStatus(notice, NoticeStatusEnums.NoticeStatus.REJECT);
	}*/

	@PutMapping("generate/{bizNo}/{checkquantity}")
    @Operation(summary = "生成检验样本", description = "生成检验样本", method = "PUT")
    public Result<Object> generate(@PathVariable(name = "bizNo", required = true) String bizNo,
								 @PathVariable(name = "checkquantity", required = true) String checkQuantity) {
    	InspectionBill bill = inspectionBillService.getById(InspectionBill.class, bizNo);
		if (bill.getCheckStatus().equals(InspectionEnums.CheckStatus.FINISH.getCode())){
			return Result.error("单据已检验完成，不能重新生成检验样本！");
		}
		if (bill.getCheckStatus().equals(InspectionEnums.CheckStatus.CHECKING.getCode())){
			return Result.error("单据正在检验中，不能重新生成检验样本！");
		}
		BigDecimal quantity = bill.getQuantity();
		if (quantity.compareTo(new BigDecimal(checkQuantity))<0){
			return Result.error("检验数量不能大于报检数量！");
		}
		bill.setCheckQuantity(new BigDecimal(checkQuantity));
		return inspectionBillService.generateSimple(bill);
    }

	@GetMapping("listbynos/{bizNos}")
	@Operation(summary = "根据bizNos获取对应多个质检单", description = "根据bizNos获取对应多个质检单，多个bizNo之间用英文逗号分隔", method = "GET")
	public Result<List<InspectionBill>> listByNos(@PathVariable(name = "bizNos", required = true) String bizNos) {
		return inspectionBillService.listByNos(bizNos);
	}

	@GetMapping("record/list")
	@Operation(summary = "检验记录报表 ", description = "检验记录报表 ", method = "GET")
	public Result<List<VInspectionBillRecord>> recordList(Criteria criteria) throws UnsupportedEncodingException {
		List<VInspectionBillRecord> list = inspectionBillRecordService.list(criteria);
		return Result.OK(list);
	}

	@GetMapping("record/page")
	@Operation(summary = "检验记录报表 ", description = "检验记录报表 ", method = "GET")
	public Result<Page<VInspectionBillRecord>> recordPage(Criteria criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
		Pageable pageAble = PageRequest.of(pageNo-1, pageSize);
		Page<VInspectionBillRecord> page = inspectionBillRecordService.listPage(pageAble, criteria);
		return Result.OK(page);
	}
}
